import csv
import io
import chardet
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.conn import *
from libs.utils import *

alarm_records_bp = Blueprint('alarm_records', __name__)

@alarm_records_bp.route('/api/get_alarm_records', methods=['GET'])
@jwt_required()
def get_alarm_records():
    client_id = request.args.get('client_id')
    plan_id = request.args.get('plan_id')
    alarm_time = request.args.get('alarm_time')
    alarm_content = request.args.get('alarm_content')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    sql = "FROM alarm_records WHERE 1=1"
    params = []
    if client_id != None and client_id != '':
        sql += " AND client_id = ?"
        params.append(client_id)
    if plan_id != None and plan_id != '':
        sql += " AND plan_id = ?"
    if alarm_time != None and alarm_time != '':
        sql += " AND alarm_time like ?"
        params.append('%'+alarm_time+'%')
    if alarm_content != None and alarm_content != '':
        sql += " AND alarm_content like ?"
        params.append('%'+alarm_content+'%')
    offset = (page_current - 1) * page_size
    rows = fetchall("SELECT * " + sql + " ORDER BY alarm_time DESC LIMIT ?, ?", tuple(params + [offset, page_size]))
    total_count = fetchvalue("SELECT COUNT(*) " + sql, tuple(params))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }

@alarm_records_bp.route('/api/alarm_record_read', methods=['POST'])
@jwt_required()
def alarm_record_read():
    alarm_id = request.json.get('alarm_id')
    execute("UPDATE alarm_records SET alarm_read = 1 WHERE alarm_id = ?", (alarm_id,))
    return { 'status': 'ok', 'data': 'success' }

@alarm_records_bp.route('/api/get_new_alarm_records', methods=['POST'])
@jwt_required()
def get_new_alarm_records():
    min_alarm_id = int(request.json.get('min_alarm_id'))
    # 获取当前时间并计算24小时前的时间
    one_day_ago = datetime.now() - timedelta(hours=24)
    formatted_one_day_ago = one_day_ago.strftime('%Y-%m-%d %H:%M:%S')
    rows = fetchall("SELECT * FROM alarm_records WHERE alarm_id > ? and alarm_time > ? ORDER BY alarm_id DESC LIMIT 20", (min_alarm_id, formatted_one_day_ago))
    return { 'status': 'ok', 'data': rows}
